﻿using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Manager.Dto;
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace RXY_Mall.Services.Manager
{
    public class ManagerService : IManagerService
    {
        private RXY_MallContext db;

        public ManagerService()
        {
            db = new RXY_MallContext();
        }

        /// <summary>
        /// 添加公司
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddManager(AddManagersInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var companys = await db.gw_companys.ToListAsync();
                var shops = await db.gw_shops.ToListAsync();
                foreach (var item in input.managers)
                {
                    var company_id = 0;
                    var shop_id = 0;
                    if (!string.IsNullOrWhiteSpace(item.api_shop_id))
                    {
                        var shop = shops.FirstOrDefault(c => c.api_shop_id == item.api_shop_id);
                        if (shop == null)
                        {
                            result.msg = "店铺不存在";
                            return result;
                        }
                        shop_id = shop.id;
                        if (shop.company_id > 0)
                        {
                            company_id = (int)shop.company_id;
                        }
                        else
                        {
                            result.msg = "公司不存在";
                            return result;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(item.api_company_id))
                        {
                            result.msg = "公司编号或店铺编号至少一个不能为空";
                            return result;
                        }
                        var company = companys.FirstOrDefault(c => c.api_company_id == item.api_company_id);
                        if (company == null)
                        {
                            result.msg = "公司不存在";
                            return result;
                        }
                        company_id = company.id;
                    }

                    var manager = await db.gw_managers.FirstOrDefaultAsync(c => c.user_name == item.mobile);

                    if (manager != null)
                    {
                        result.msg = "管理员已存在";
                        return result;
                    }
                    manager = new gw_manager()
                    {
                        company_id = company_id,                     
                        user_name = item.mobile,
                        role_type = item.manager_type,
                        password = "123456",
                        api_manager_id = item.api_manager_id,
                        add_time = DateTime.Now,
                        deleted = false,
                    };
                    if (shop_id>0)
                    {
                        manager.shop_id = shop_id;
                    }
                    db.gw_managers.Add(manager);
                }
                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }

        public async Task<ResponseService<LoginOutput>> GetManager(LoginInput input)
        {
            ResponseService<LoginOutput> result = new ResponseService<LoginOutput>();
            result.code = 0;
            try
            {
                var manager = await db.gw_managers
                .FirstOrDefaultAsync(u => u.user_name == input.user_name);

                if (manager == null || manager.deleted == true)
                {
                    result.msg = "该非法访问，你已加入黑名单";
                    return result;
                }

                if (manager.status == 1)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                string error = "";
                if (!IsPassword(manager.id, input.password, 0, out error))
                {
                    result.msg = error;
                    return result;
                }
                //添加用户登录日志
                gw_security_login login_log = new gw_security_login()
                {
                    add_time = DateTime.Now,
                    ip = DcRequest.GetIP(),
                    type = (int)LoginType.密码登录,
                    user_id = manager.id,
                };
                db.gw_security_logins.Add(login_log);

                manager.token = Guid.NewGuid().ToString();
                db.Entry(manager).Property(u => u.token).IsModified = true;
                await db.SaveChangesAsync();

                LoginOutput output = new LoginOutput()
                {
                    manager_id = manager.id,
                    token = manager.token,
                    user_name = manager.user_name,
                };

                result.code = 1;
                result.msg = "登录成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;

        }

        /// <summary>
        /// 验证密码是否正确
        /// </summary>
        /// <param name="manager_id"></param>
        /// <param name="password"></param>
        /// <param name="password_type"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool IsPassword(int manager_id, string password, int password_type, out string error)
        {
            bool flag = false;
            error = "";
            var passwords = db.gw_manager_passwords.FirstOrDefault(p => p.manager_id == manager_id && p.type == password_type);

            if (passwords == null)
            {
                if (password_type == 0)
                {
                    error = "请设置登录密码";
                }
                else
                {
                    error = "请设置支付密码";
                }

                return flag;
            }

            if (passwords.block_time > DateTime.Now)
            {
                error = "密码输错次数过多，已锁30分钟";
                return flag;
            }

            //记录五次
            if (passwords.password != EncryptionHelper.EncryptText(password))
            {
                var date = DateTime.Now.AddMinutes(-30);
                var count = db.gw_manager_password_logs.Count(l => l.manager_id == manager_id && l.type == password_type && l.add_time > date);
                if (count >= 5)
                {
                    error = "30分钟内密码输出5次锁30分钟";
                    return flag;
                }
                var log = new gw_manager_password_log() { add_time = DateTime.Now, manager_id = manager_id, type = (byte)password_type };
                db.gw_manager_password_logs.Add(log);
                db.SaveChanges();
                if (count < 3)
                {
                    error = "密码错误";
                }
                else
                {
                    error = string.Format("密码输错{0}次", count);
                }

                return flag;
            }
            return true;
        }

    }
}
